package splatform.webchatbot.control;

import com.jerei.web.utils.UtilsUI;
import com.jerei.web.utils.UtilsWeb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import splatform.webchatbot.entity.BotCat;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Created by sunfeihu on 2017/3/15.
 */
@Controller
@RequestMapping(value = "/admin/webchatbot/cat")
public class BotCatControl {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping(value = "/edit")
    public String edit(Model model, HttpServletRequest request, Long id) {
        if (null == id) {
            Long typeId = UtilsWeb.getLong(request, "typeId");
            BotCat obj = new BotCat();
            obj.setType_id(typeId);
            model.addAttribute("obj", obj);
        } else {
            Map<String, Object> map = jdbcTemplate.queryForMap(" select * from bot_cat where id = ? ", new Object[]{id});
            BotCat obj = new BotCat();
            obj.setId((Long) map.get("id"));
            obj.setConfig_json((String) map.get("config_json"));
            obj.setName((String) map.get("name"));
            obj.setRemark((String) map.get("remark"));
            obj.setType_id((Long) map.get("type_id"));
            model.addAttribute("obj", obj);
        }
        return "/admin/webchatbot/cat/edit";
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public String save(BotCat obj) {
        if (null == obj.getId() || obj.getId() == null || obj.getId().equals(0L)) {
            jdbcTemplate.update(" insert into bot_cat (name,type_id,config_json,remark) values (?,?,?,?) ", new Object[]{
                    obj.getName(), obj.getType_id(), obj.getConfig_json(), obj.getRemark()
            });
        } else {
            jdbcTemplate.update(" update bot_cat set name = ? , type_id = ? , config_json = ? , remark = ? where id = ? ", new Object[]{
                    obj.getName(), obj.getType_id(), obj.getConfig_json(), obj.getRemark(), obj.getId()
            });
        }
        return UtilsUI.ok();
    }

    @RequestMapping(value = "/list")
    public String list(Model model, Long typeId) {
        model.addAttribute("typeId", typeId);
        return "/admin/webchatbot/cat/list";
    }

    @RequestMapping(value = "/page")
    @ResponseBody
    public String page(Model model, Long typeId) {
        List<Map<String, Object>> list = jdbcTemplate.queryForList(" select * from bot_cat where type_id = ? ", new Object[]{
                typeId
        });
        return UtilsUI.datagrid(list);
    }

}
